<?php
namespace Admin\Controller;

use Think\Controller;

class CommonController extends Controller
{
    protected $view_data = null;
    protected $user_id = null;
    protected $user_name = null;
    /**
     * 自动执行方法，检测是否登录
     * @return mixed
     */
    public function _initialize()
    {
        if (!empty(session('user.id')) && session('user.id') > 0) {
            $this->user_id = session('user.id');
            $this->user_name = session('user.user_name');
            return true;
        } else { //未登录跳转到登录页
            redirect(U('Login/index'));
        }
    }

    /**
     * 检测是否是PSOT提交
     * @return bool
     */
    protected function checkPost()
    {
        if (!IS_POST) {
            E('非法操作');
        }
        return true;
    }

    /**
     * ajax请求成功返回格式
     * @param null $data
     * @param int $code
     * @param string $msg
     * @return string
     */
    protected function ajaxSuccess($msg = 'success', $data = null, $code = 0)
    {
        $this->ajaxReturn(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * ajax请求错误返回格式
     * @param null $data
     * @param int $code
     * @param string $msg
     * @return string
     */
    protected function ajaxError($msg = '服务器错误', $data = null, $code = 1)
    {
        $this->ajaxReturn(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }
}